package com.example.demo2.utils;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ResponseParseUtils {
    public static  <T> List<T> parseResponse(SearchResponse searchResponse, Class<T> cls) {
        SearchHit[] hits = searchResponse.getHits().getHits();

        if (hits != null && hits.length != 0) {

            //Stream<hit>-->Stream<teacher>
            List<T> teacherList = Stream.of(hits).map(hit -> {
                String sourceAsString = hit.getSourceAsString();
                T teacher = JSON.parseObject(sourceAsString, cls);
                return teacher;
            }).collect(Collectors.toList());
            return teacherList;
        }

        return null;
    }
}
